#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode() : val(0), left(nullptr), right(nullptr) {}
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
	TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        vector<int>ret;
        queue<TreeNode*>q;
        if (root)
        {
            long maxval = LONG_MIN;
            q.push(root);
            while (!q.empty())
            {
                maxval = LONG_MIN;
                int levelsize = q.size();
                while (levelsize--)
                {
                    auto top = q.front(); q.pop();
                    maxval = max(maxval, (long)top->val);
                    if (top->left)q.push(top->left);
                    if (top->right)q.push(top->right);
                }
                ret.push_back(maxval);
            }
        }
        return ret;
    }
};